<template>
  <textarea v-model="currentValue"
            :placeholder="placeholder"
            :readonly="readonly"
            :maxlength="max"
            :style="style"
            :rows="rows"
            :cols="cols"
            @blur="onBlur"
            @focus="setAutoHeight"
            @input="setAutoHeight"
            ref="textarea">
  </textarea>
</template>

<script>
export default {
  name:'comp-textarea',
  props: {
    max: Number,
    value: {
      type: String,
      default: ''
    },
    placeholder: String,
    rows: {
      type: Number,
      default: 2
    },
    cols: {
      type: Number,
      default: 30
    },
    readonly: {
      type: Boolean,
      default: false
    },
    ellipsis: {
      type: Boolean,
      default: false
    },
    autoheight: {
      type: Boolean,
      default: true
    }
  },
  created: function () {
    this.currentValue = this.value;
  },
  data: function () {
    return {
      currentValue: '',
      style: ''
    };
  },
  watch: {
    value: function (val) {
      this.currentValue = val;
    },
    currentValue: function (newVal) {
      if(this.max && newVal > this.max) {
        this.currentValue = newVal.toString().slice(0, this.max);
      }
      this.$emit('on-change', this.currentValue);
      this.$emit('input', this.currentValue);
    }
  },
  methods: {
    autoSetHeight: function () {
      this.style = 'height:' + this.$el.scrollHeight + 'px';
    },
    onBlur: function () {
      if(this.ellipsis) {
        this.style = '';
      } else {
        this.autoSetHeight();
      }
      this.$emit('blur', this.currentValue);
    },
    setAutoHeight: function () {
      if(this.autoheight) {
        this.autoSetHeight();
      }
    }
  },
  mounted: function () {
    if(!this.ellipsis) {
      var $this = this;
      setTimeout(function () {
        $this.autoSetHeight();
      }, 100);
    }
  },
  updated: function () {
    if(!this.ellipsis) {
      var $this = this;
      setTimeout(function () {
        $this.autoSetHeight();
      }, 100);
    }
  }
};
</script>
